<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Tabs Example</title>
    <link rel="stylesheet" href="../highlight/styles/github-dark.css">
    <script src="../highlight/highlight.min.js"></script>
    <!-- <script>hljs.highlightAll();</script> -->
    <script>
        // 定义OneTabData结构体
        class OneTabData {
            constructor(name, code) {
                this.tabName = name;
                this.tabData = code;
            }
        }

        // 定义CodeViewData结构体
        class CodeViewData {
            constructor() {
                this.activeTabName = "";
                this.allTabData = [];
            }

            saveStorage()
            {
                localStorage.setItem("activeTabName", this.activeTabName);
                localStorage.setItem("allTabData", JSON.stringify(this.allTabData));
            }

            loadStorage()
            {
                this.activeTabName = localStorage.getItem("activeTabName");
                this.allTabData = JSON.parse(localStorage.getItem("allTabData"));
                if(this.allTabData == null)
                {
                    this.activeTabName = "";
                    this.allTabData = [];
                }
                console.log(JSON.stringify(this));
            }

            setActive(tabName)
            {
                this.activeTabName = tabName;
            }

            addTabData(tabData) {
                this.allTabData.push(tabData);
            }

            removeTabData(tabName) {
                var index = -1;
                for(let i = 0; i < this.allTabData.length; ++i){
                    if(this.allTabData[i].tabName == tabName)
                        index = i;
                }
                if (index > -1) {
                    this.allTabData.splice(index, 1);
                }
                if(this.allTabData.length == 0)
                {
                    this.activeTabName = "";
                }
            }
        }
        let codeViewData = new CodeViewData();
        code = `
    #include "session_manager.h"
    #include "nlohmann/json.hpp"
    #include "../common/common.h"
    
    namespace ArrowWebSocket
    {
    
    CSessionManager::CSessionManager()
    {
    }
    
    CSessionManager::~CSessionManager()
    {
        Deini();
    }
    
    void CSessionManager::Init(asio::io_context& ioContext)
    {
        m_pTimer = new asio::steady_timer(ioContext);
    }
    
    void CSessionManager::Run()
    {
        DoReadQueue();
        return;
    }
    
    void CSessionManager::Deini()
    {
        if(m_pTimer != nullptr)
        {
            m_pTimer->cancel();
            delete m_pTimer;
            m_pTimer = nullptr;
        }
    }
    
    void CSessionManager::AddSession(SharedPtrISession pSession)
    {
        if(m_setSessions.find(pSession) != m_setSessions.end())
            return;
    
        if(m_setMsgSrcInfo.size() > 0 )
        {
            std::string strTmpAllMsgSrcInfo;
            nlohmann::json j;
            for (auto& it : m_setMsgSrcInfo)
            {
                j.push_back(it);
            }
            strTmpAllMsgSrcInfo = j.dump();
            pSession->PutAllMsgSrcInfo(strTmpAllMsgSrcInfo);
        }
    
        m_setSessions.insert(pSession);
    }
    
    void CSessionManager::RemoveSession(SharedPtrISession pSession)
    {
        m_setSessions.erase(pSession);
        if(m_setSessions.size() == 0)
        {
            m_setMsgSrcInfo.clear();
        }
    }
    
    void CSessionManager::PutMsg(const SharedPtrMsg& pMsg)
    {
        m_msgQueue.Push(pMsg);
    }
    
    void CSessionManager::DoReadQueue()
    {
        // if (m_msgQueue.Empty())
        // {
        //     // 启动定时器 10毫秒后再次调用
        //     m_pTimer->expires_after(std::chrono::milliseconds(10));
        //     m_pTimer->async_wait([this](beast::error_code ec) {
        //         if (!ec)
        //         {
        //             DoReadQueue();
        //         }
        //     });
        //     return;
        // }
        // SharedPtrMsg pMsg;
        // if( false == m_msgQueue.Pop(pMsg))
        // {
        //     return;
        // }
    
        // auto it = m_setMsgSrcInfo.find(pMsg->SrcInfo());
        // if(it == m_setMsgSrcInfo.end())
        // {
        //     m_setMsgSrcInfo.insert(pMsg->SrcInfo());
        //     nlohmann::json j;
        //     j["msg_type"] = static_cast<int32_t>(EmMsgType::AllMsgSrcInfo);
        //     for (auto& it : m_setMsgSrcInfo)
        //     {
        //         j["msg_src_info"].push_back(it);
        //     }
        //     std::string strtmp = j.dump();
    
        //     for (auto& it : m_setSessions)
        //     {
        //         it->PutAllMsgSrcInfo(strtmp);
        //     }
        // }
    
        // for (auto& it : m_setSessions)
        // {
        //     it->PutMsg(pMsg);
        // }    
        // DoReadQueue();
    }
    
    int32_t CSessionManager::Count()
    {
        return m_setSessions.size();
    }
    
    } // namespace ArrowWebSocket
`;
        window.onbeforeunload = function()
        {
            codeViewData.saveStorage();
        }

        window.onload = function()
        {
            createPath("main.cpp");
            codeViewData.loadStorage();
            for(let i = 0; i < codeViewData.allTabData.length; ++i)
            {
                createTab(codeViewData.allTabData[i].tabName, codeViewData.allTabData[i].tabData);
            }
            if(codeViewData.activeTabName.length > 0)
                activateTab(codeViewData.activeTabName);
        }

        function togglePathList() {
            var container = document.getElementById('path-list-container');
            if(container == null)
                console.log("container is null");
            container.classList.toggle('hide');
            var toggleBtn = document.getElementById('toggle-path-list-btn');
            toggleBtn.innerHTML = container.classList.contains('hide') ? 'Show' : 'Hide';
        }

        function createOrActivateTab(tabName) {

            var existingTab = document.getElementById(tabName);
            var existingTabContent = document.getElementById(tabName + '-content');

            if (existingTab) {
                activateTab(tabName);
            } else {
                createTab(tabName, code);
                codeViewData.addTabData(new OneTabData(tabName, code));
                activateTab(tabName);
            }
        }

        function createTab(tabName, tabData)
        {
            var tabs = document.getElementById('tabs');
            var tabContentContainer = document.getElementById('tab-content-container');

            var newTab = document.createElement('div');
            newTab.className = 'tab';
            newTab.id = tabName;
            newTab.innerHTML = `${tabName} <span class="close-btn" onclick="closeTab(event, '${tabName}')"> x </span>`;
            newTab.onclick = function() { activateTab(tabName); };

            var newTabContent = document.createElement('div');
            newTabContent.className = 'tab-content';
            newTabContent.id = tabName + '-content';
            newTabContent.innerHTML = `<pre><code class="cpp">${tabData}</code></pre>`;
            newTabContent.querySelectorAll('pre code').forEach((block) => {
                hljs.highlightBlock(block);
            });

            tabs.appendChild(newTab);
            tabContentContainer.appendChild(newTabContent);
        }

        function activateTab(tabName) {

            tab = document.getElementById(tabName);
            tabContent = document.getElementById(tabName + "-content")

            var i, tablinks, tabcontents;
            tablinks = document.getElementsByClassName('tab');
            for (i = 0; i < tablinks.length; i++) {
                tablinks[i].classList.remove('active');
            }

            tabcontents = document.getElementsByClassName('tab-content');
            for (i = 0; i < tabcontents.length; i++) {
                tabcontents[i].classList.remove('active');
            }

            tab.classList.add('active');
            tabContent.classList.add('active');
            codeViewData.setActive(tabName);

            console.log(JSON.stringify(codeViewData));
        }

        function closeTab(event, tabName) {
            event.stopPropagation();
            var tab = document.getElementById(tabName);
            var tabContent = document.getElementById(tabName + '-content');
            tab.remove();
            tabContent.remove();

            codeViewData.removeTabData(tabName);
            console.log(JSON.stringify(codeViewData));

            var tabs = document.getElementsByClassName('tab');
            if (tabs.length > 0) {
                <!-- activateTab(tabs[0], document.getElementById(tabs[0].id + '-content'), tabs[0].id); -->
                activateTab(tabs[0].id);
            }
        }

        function createPath(pathName)
        {
            var pathListContainer = document.getElementById('path-list-container');
            var newPath = document.createElement('div');
            newPath.className = "path";
            newPath.onclick = function() { createOrActivateTab(pathName); };
            newPath.innerHTML = pathName;
            pathListContainer.appendChild(newPath)

        }
    </script>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            height: 100%;
            width: 100%;
            font-family: Arial, sans-serif;
        }

        .main-frame
        {
            display: flex;
            flex-direction: column;
            background-color: green;
            width: 100%;
            height: 100%;
        }

        .top-bar {
            display: flex;
            flex-direction: row;
            flex: 0 0 25px;
            background-color: steelblue;
            color: white;
           
            align-items: center;
            padding: 0 10px;
            box-sizing: border-box;
            z-index: 1000;
        }

        .code-frame
        {
            display: flex;
            flex-direction: row;
            flex : 1;
            background-color: rgb(180, 70, 98);
            color: white;
            width: 100%;
            height: calc(100% - 25px);
        }

        .path-list
        {
            flex: 0 0 250px;
            background-color: rgb(100, 100, 100);
            color: white;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            padding-top: 10px;
            padding-left: 10px;
        }

        .path
        {
            padding-top: 5px;
            background-color:black;
        }

        .code-view
        {
            flex: 1;
            overflow-y: auto;
        }

        .tabs {
            display: flex;
            border-bottom: 1px solid #ccc;
        }

        .tab {
            padding: 10px;
            cursor: pointer;
            border: 1px solid #ccc;
            border-bottom: none;
            margin-right: 5px;
            position: relative;
            display: flex;
            align-items: center;
        }
        
        .tab .close-btn {
            margin-left: 10px;
            cursor: pointer;
            color: red;
            font-weight: bold;
        }

        .tab.active {
            background-color: greenyellow;
            font-weight: bold;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .hide {
            display: none;
        }
    </style>
</head>
<body>
    <div class="main-frame">
        <div class="top-bar">
            <button onclick="togglePathList()" id="toggle-path-list-btn">Hide</button>
            <span style="margin-left: 10px;">This is the top bar</span>
        </div>
        <div class="code-frame">
            <div class="path-list"  id="path-list-container">
                <div class="path" onclick="createOrActivateTab('index.html')">index.html</div>
                <div class="path" onclick="createOrActivateTab('styles.css')">styles.css</div>
                <div class="path" onclick="createOrActivateTab('script.js')">script.js</div>
            </div>
            <div class="code-view">
                <div class="tabs" id="tabs"></div>
                <div id="tab-content-container"></div>
            </div>
        </div>
</div>
</body>
</html>
